/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-22 14:06:57
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-07-03 15:31:16
 * @FilePath: \vite-project\src\pages\operateSystem\menu\Index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { addMenu, delMenu, getMenuChildrenByParentId, getMenuTree, modifyMenu } from 'apis/menu';
import MenuTree from 'components/SearchMenuTree/Index';
import CommonDrawer from 'components/common/CommonDrawer';
import MenuForm from 'components/menu/MenuForm';
import { MENU_MODULE_TYPE_ENUM, MENU_TYPE_ENUM } from 'constant';
import useTableAction from 'hooks/useTableAction';
import { ProTable } from '@ant-design/pro-components';
import { Button, Divider, Space, Tabs, Tag, message } from 'antd';
import { useEffect, useRef, useState } from 'react';

const MenuManagePage: React.FC = () => {
    const [queryCondition, setQueryCondition] = useState<string | null>(null);
    const menuTreeRef = useRef<{
        refresh?: any;
    }>();

    // table
    const [tableLoading, setTableLoading] = useState(false);
    const tablecolumns = [
        {
            title: '菜单名称',
            dataIndex: 'label',
            key: 'label',
            ellipsis: true,
        },
        {
            title: '菜单类型',
            dataIndex: 'type',
            key: 'type',
            valueType: 'select',
            valueEnum: MENU_TYPE_ENUM,
            width: 80,
        },
        {
            title: '菜单属性',
            dataIndex: 'module',
            key: 'module',
            valueType: 'select',
            width: 80,
            valueEnum: MENU_MODULE_TYPE_ENUM,
        },
        {
            title: '访问路径',
            dataIndex: 'path',
            key: 'path',
            ellipsis: true,
        },
        {
            title: '文件路径',
            dataIndex: 'filepath',
            key: 'filepath',
            ellipsis: true,
        },
        {
            title: '权限标识',
            width: 150,
            dataIndex: 'power',
            key: 'power',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => (
                <Space>
                    <a
                        key='link'
                        onClick={() => {
                            // 移动端涉及上传图标回显
                            record.pictureId =
                                record.pictureId && record.module === 2
                                    ? [
                                          {
                                              attachId: record?.pictureId,
                                              url: record?.pictureUrl,
                                          },
                                      ]
                                    : [];
                            handleEdit(record);
                        }}
                    >
                        修改
                    </a>
                    <a
                        key='link2'
                        onClick={() =>
                            handleDel(
                                () =>
                                    delMenu({
                                        id: record.id,
                                    }),
                                {
                                    successMsg: '确认菜单删除',
                                    successCallback: () => {
                                        menuTreeRef?.current?.refresh?.();
                                    },
                                },
                            )
                        }
                    >
                        删除
                    </a>
                    <a key='link3' onClick={() => handleCopy(record)}>
                        复制
                    </a>
                </Space>
            ),
        },
    ];
    const [parentId, setParentId] = useState('');
    const [parentNode, setParentNode] = useState(null);
    const [module, setModule] = useState('1');
    const {
        title,
        visible,
        tableRef,
        editFormData,
        setEditFormData,
        handleEdit,
        handleAdd,
        handleDel,
        handleClose,
        refresh,
    } = useTableAction('菜单');

    const handleCopy = (data) => {
        setEditFormData({
            ...data,
            id: void 0,
            ...(data?.module === 2 && data?.pictureId
                ? {
                      pictureId: [
                          {
                              attachId: data?.pictureId,
                              url: data?.pictureUrl,
                          },
                      ],
                  }
                : {}),
        });
        handleAdd();
    };

    // form
    const [treeData, setTreeData] = useState<any[]>([]);

    const onSelect = (_selectedKeys: any, { selected, node }: any) => {
        if (selected) {
            setParentId(node.id);
            setParentNode(node);
        } else {
            setParentId('');
            setParentNode(node);
        }
    };
    const onUpdateTreeData = (data: any[]) => {
        setTreeData(data);
    };
    const onSubmit = async (form: any, loadinCallback?: () => void, closeModalCallback?: () => void) => {
        const params = {
            ...(editFormData.id ? { id: editFormData.id } : {}),
            ...form,
            pictureId: form.module === 2 ? form?.pictureId?.map((item) => item.attachId)?.[0] : void 0,
        };
        try {
            if (editFormData.id) {
                await modifyMenu(params);
            } else {
                await addMenu(params);
            }
            message.success(`菜单${editFormData?.id ? '编辑' : '创建'}成功`);
            refresh();
            closeModalCallback?.();
            menuTreeRef.current?.refresh?.();
        } catch (error) {
            //
        } finally {
            loadinCallback?.();
        }
    };

    const isFirst = useRef(true);
    useEffect(() => {
        if (isFirst.current) {
            isFirst.current = false;
        } else {
            menuTreeRef?.current?.refresh?.();
        }
    }, [module]);
    return (
        <div className='h-100%'>
            {/* <Tabs
                className='page-tab bg-white mb-12px p-l-20px'
                onChange={(key: string) => setModule(key)}
                activeKey={module}
                items={[
                    {
                        label: 'PC',
                        key: '1',
                    },
                    {
                        label: '移动',
                        key: '2',
                    },
                ]}
            ></Tabs> */}
            <div className='flex justify-center h-100%'>
                <div className='w-300px mr-12px bg-white flex flex-col' style={{ height: 'calc(100vh - 69px)', minHeight: '400px' }}>
                    <div className='px-12px  text-right pt-12px'>
                        <Button
                            disabled={!!parentNode?.children?.length}
                            type='primary'
                            onClick={() =>
                                handleDel(
                                    () =>
                                        delMenu({
                                            id: parentNode?.id,
                                        }),
                                    {
                                        successMsg: '确认菜单删除',
                                        successCallback: () => {
                                            setParentId('');
                                            setParentNode(null);
                                            menuTreeRef?.current?.refresh?.();
                                        },
                                    },
                                )
                            }
                        >
                            删除
                        </Button>
                        <Divider className='my-12px'></Divider>
                    </div>

                    <div className='flex p-12px flex-1'>
                        <MenuTree
                            parentId={parentId}
                            queryCondition={queryCondition}
                            onSelect={onSelect}
                            onUpdateTreeData={onUpdateTreeData}
                            fieldNamesTitle='label'
                            fieldNamesKey='id'
                            api={() => {
                                return getMenuTree({
                                    // 1-PC端，2-移动端
                                    module: module,
                                    name: queryCondition,
                                });
                            }}
                            treeKeyInName='menuTree'
                            ref={menuTreeRef}
                        ></MenuTree>
                    </div>
                </div>
                <div className='flex-1 bg-white overflow-hidden'>
                    <ProTable
                        params={{
                            ...(parentId ? { parentId } : {}),
                            module: module,
                        }}
                        loading={tableLoading}
                        columns={tablecolumns}
                        scroll={{
                            y: `calc(100vh - 247px)`,
                        }}
                        search={false}
                        pagination={{
                            showQuickJumper: true,
                            showSizeChanger: true,
                        }}
                        toolBarRender={() => [
                            <Button
                                type='primary'
                                onClick={() =>
                                    handleAdd(() =>
                                        setEditFormData({
                                            parentId,
                                            module: Number(module),
                                        }),
                                    )
                                }
                            >
                                新建
                            </Button>,
                        ]}
                        actionRef={tableRef}
                        request={async (params) => {
                            if (!parentId) {
                                return Promise.resolve({
                                    data: [],
                                });
                            }
                            setTableLoading(true);
                            let totalPages = 0;
                            let data = [];
                            try {
                                const res: any = await getMenuChildrenByParentId({
                                    parentId: params.parentId,
                                    module: params.module,
                                });
                                data = res?.recordDatas || [];
                                totalPages = res?.length;
                            } catch (error) {
                                totalPages = 1;
                                data = [];
                            } finally {
                                setTableLoading(false);
                            }
                            return Promise.resolve({
                                data,
                                success: true,
                                total: totalPages,
                            });
                        }}
                    />
                </div>
            </div>
            <CommonDrawer
                title={title}
                open={visible}
                close={handleClose}
                onSubmit={onSubmit}
                initFormData={editFormData}
            >
                <MenuForm parentId={parentId} treeData={treeData}></MenuForm>
            </CommonDrawer>
        </div>
    );
};

export default MenuManagePage;
